﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoBehaviour {
    public static AudioManager Instance;
    private float bgmvolume = 1;
    public float BgmVolume { get { return bgmvolume; } set { bgm.volume = value; } }
    public AudioSource bgm;
    private float emVolume = 1;
    List<AudioSource> audioSources = new List<AudioSource> ();
    void Awake () {
        if (AudioManager.Instance != null) {
            Destroy (this.gameObject);
            return;
        }
        Instance = this;
    }
    public void SetEMVolume (float value) {
        value = Mathf.Clamp (value, 0, 1);
        for (int i = 0; i < audioSources.Count; i++)
        {
            audioSources[i].volume = value;
        }
        emVolume = value;
    }
    public void PlayAudio (AudioClip clip) {
        AudioSource au = null;

        if (audioSources.Count <= 0) {
            au=CreateAudioSources();

        }
        else
        {
            for (var i = 0; i < audioSources.Count; i++)
            {
                if (!audioSources[i].isPlaying)
                {
                    au = audioSources[i];
                    break;
                }
            }
            if (au == null)
            {
                au = CreateAudioSources();
            }
        }

        au.clip = clip;
        au.Play ();

    }

    AudioSource CreateAudioSources()
    {
        AudioSource au = null;
        GameObject g = new GameObject();
        g = Instantiate(g, transform);
        au = g.AddComponent<AudioSource>();
        g.name = "audio" + audioSources.Count;
        au.playOnAwake = false;
        au.loop = false;
        au.volume = emVolume;
        audioSources.Add(au);
        return au;
    }
}